package com.macrosoft.frpd.utils;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;

import com.macrosoft.frpd.application.IConstants;

public class Util {

	// ===========================================================
	// Constants
	// ===========================================================
	public static String REGEX_HTML_TO_XML = "(&[^\\s]+?;)";
	// ===========================================================
	// RegEx
	// ===========================================================

	public static String[] extractTorrentInfoXML(String pText) {
		String[] result = null;
		String re1 = ".*?"; // Non-greedy match on filler
		String re2 = "([+-]?\\d*\\.\\d+)(?![-+0-9\\.])"; // Float 1
		String re3 = ".*?"; // Non-greedy match on filler
		String re4 = "((?:[a-z][a-z]+))"; // Word 1
		String re5 = ".*?"; // Non-greedy match on filler
		String re6 = "(\\d+)"; // Integer Number 1
		String re7 = ".*?"; // Non-greedy match on filler
		String re8 = "(\\d+)"; // Integer Number 2

		Pattern pattern = Pattern.compile(re1 + re2 + re3 + re4 + re5 + re6 + re7 + re8, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
		Matcher matcher = pattern.matcher(pText);
		if (matcher.find()) {
			int length = matcher.groupCount();
			result = new String[length];
			for (int i = 0; i < length; i++) {
				result[i] = matcher.group(i + 1);
			}
		}
		return result;
	}

	/**
	 * @see <b>IgnoreContentType</b> true, and default <b>USER AGENT</b> defined in IConstants
	 * @param pURL
	 *            Url to connect with
	 * @return {@code Connection } object
	 * @throws IOException
	 * 
	 */
	public static Connection jSoupDefaultConnect(String pURL) throws IOException {
		return Jsoup.connect(pURL).ignoreContentType(true).userAgent(IConstants.USER_AGENT).timeout(IConstants.TIME_OUT);
	}

	public static ProgressDialog showDialog(final Context pContext, final String title, final String msg) {
		return ProgressDialog.show(pContext, title, msg, true);

	}

	public static String cleanUpXML(String in_string) {
		if (in_string == null)
			return null;

		StringBuilder sbOutput = new StringBuilder();
		char ch;

		for (int i = 0; i < in_string.length(); i++) {
			ch = in_string.charAt(i);
			if ((ch >= 0x0020 && ch <= 0xD7FF) || (ch >= 0xE000 && ch <= 0xFFFD) || ch == 0x0009 || ch == 0x000A || ch == 0x000D) {
				sbOutput.append(ch);
			}
		}
		return sbOutput.toString();
	}
}